/*
 * Created on Sun Sep 17 2017
 * @flow
 * Copyright (c) 2017 jianglinjie
 */
'use strict';

import type { NetStrategy } from './NetStrategy';
import * as ResponseType from '../constants/ResponseType';
import NetworkReponse from './NetworkReponse';
import type NetRequest from '../request/NetRequest';

export default class FetchStrategy implements NetStrategy {
  async start(request: NetRequest): Promise<NetworkReponse> {
    let fetchRequest = this.constructFetchRequest(request);

    let response = await fetch(fetchRequest);
    let body = undefined;

    switch (request.responseType) {
      case ResponseType.ARRAY_BUFFER_TYPE: {
        body = await response.arrayBuffer();
        break;
      }
      case ResponseType.BLOB_TYPE: {
        body = await response.blob();
        break;
      }
      case ResponseType.JSON_TYPE: {
        body = await response.json();
        break;
      }
      case ResponseType.TEXT_TYPE: {
        body = await response.text();
        break;
      }
      case ResponseType.FORM_DATA_TYPE: {
        body = await response.formData();
        break;
      }
      default: {
        break;        
      }
    }

    return new NetworkReponse(response.status, body);
  }

  constructFetchRequest(request: NetRequest): Request {
    let requestInit: Object = { method: request.method };

    if (request.headers && Object.keys(request.headers).length) {
      requestInit.headers = new Headers(request.headers);
    } else {
      requestInit.headers = new Headers();
    }

    if (request.body) {
      requestInit.body = request.body;
    }

    requestInit.mode = 'cors';

    let fetchRequest = new Request(request.requestUrl, requestInit);

    return fetchRequest;
  }
}
